package org.mog.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import context.JwtContext;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mog.gateway.config.AuthProperties;
import org.mog.gateway.config.JwtProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import utils.JwtUtil;

import java.util.List;

@RequiredArgsConstructor
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request对象
        ServerHttpRequest request = exchange.getRequest();

        //判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())) {
            //放行
            return chain.filter(exchange);
        }

        //获取token
        String token = null;
        List<String> headers = request.getHeaders().get("token");
        System.out.println("headers=" + headers);
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }
        Long id;
        //校验并解析token
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            log.info("claims={}", claims);
            id = Long.valueOf(claims.get(JwtContext.ID).toString());
        } catch (Exception e) {
            //拦截，设置状态码为401（401就表示未登录）
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 传递用户信息
        System.out.println(id);
        String userInfo = id.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        //放行，使用修改后的exchange
        return chain.filter(serverWebExchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExclude(String path) {
        for (String excludePathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePathPattern, path)) {
                return true;
            }
        }

        return false;
    }
}
